package udpInvoker.main;

import udpInvoker.util.UdpUtils;

import java.util.HashMap;
import java.util.Iterator;

/**
 * Created by IntelliJ IDEA.
 * User: esr
 * Date: 13.okt.2008
 * Time: 14:18:41
 * Copyright 2008  Espen Skjervold, FFI
 */
public class UdpUnicastReceiver implements Runnable{

    private static UdpUnicastReceiver instance;
    private HashMap<MessageSubscriber, Object> subscribers;

    private  String unicastAddress;
    private  int port;
    private int transportType=2; //unicast



    public static UdpUnicastReceiver getInstance(String address, int port) {
        if (instance==null)
            instance =new UdpUnicastReceiver(address, port);

        return instance;

    }

    private UdpUnicastReceiver(String address, int port) {
        unicastAddress=address;
        this.port= port;

        subscribers = new HashMap<MessageSubscriber, Object>();
        Thread listenerThread = new Thread(this);
        listenerThread.start();

    }

    public void setUnicastAddress(String address, int port) {
        unicastAddress=address;
        this.port=port;
    }

    public synchronized void subscribe(MessageSubscriber messageSubscriber) {
        if (!subscribers.containsKey(messageSubscriber))
            subscribers.put(messageSubscriber, null);
    }


    public void run() {


        while (true) {

            try {

                System.out.println("waiting for unicast datagram...");
                byte[] buffer = UdpUtils.receiveMessageBuffer(transportType, unicastAddress, port, true);
                System.out.println("Received unicast datagram!");

                HashMap subs = (HashMap) subscribers.clone();
                Iterator iterator = subs.keySet().iterator();
                while (iterator.hasNext()) {
                    MessageSubscriber subscriber = (MessageSubscriber) iterator.next();
                    subscriber.addMessageToQue(buffer);
                }


            } catch (Exception e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }


        }



    }
}